package com.css.upms.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.css.common.core.constent.CommonConstant;
import com.css.upms.api.dto.AreaTree;
import com.css.upms.api.dto.DeptTree;
import com.css.upms.api.entity.SysArea;
import com.css.upms.api.entity.SysDept;
import com.css.upms.api.vo.TreeUtil;
import com.css.upms.biz.mapper.SysAreaMapper;
import com.css.upms.biz.service.SysAreaService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 区域管理
 *
 * @author hanyx
 * @date 2019-06-06 15:01:08
 */
@Service("sysAreaService")
public class SysAreaServiceImpl extends ServiceImpl<SysAreaMapper, SysArea> implements SysAreaService {

    /**
     * 区域管理简单分页查询
     *
     * @param sysArea 区域管理
     * @return
     */
    @Override
    public IPage<SysArea> getSysAreaPage(Page<SysArea> page, SysArea sysArea) {
        return baseMapper.getSysAreaPage(page, sysArea);
    }

    /**
     * 查询全部部门树
     *
     * @return 树
     */
    @Override
    public List<AreaTree> listAreaTrees() {
        List<SysArea> areaList = this.list();
        return getDeptTree(areaList, CommonConstant.ROOT_NODE_VAL);
    }

    /**
     * 构建区域树
     *
     * @param areas 区域
     * @return
     */
    private List<AreaTree> getDeptTree(List<SysArea> areas, String rootNodeVal) {
        List<AreaTree> treeList = areas.stream()
                .filter(area -> !area.getId().equals(area.getParentId()))
                .map(area -> {
                    AreaTree node = new AreaTree();
                    node.setId(String.valueOf(area.getId()));
                    node.setParentId(String.valueOf(area.getParentId()));
                    node.setTitle(area.getName());
                    node.setName(area.getName());
                    node.setCode(area.getCode());
                    return node;
                }).collect(Collectors.toList());
        return TreeUtil.buildByRecursive(treeList, rootNodeVal);
    }

}
